package com.chain.BrotherExchange.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chain.BrotherExchange.BuildConfig;
import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.CountryCodeList;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.RegisterViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.geetest.sdk.Bind.GT3GeetestBindListener;
import com.geetest.sdk.Bind.GT3GeetestUtilsBind;

import org.json.JSONObject;

import butterknife.Bind;

import static com.chain.BrotherExchange.viewmodel.VerificationManage.verifyMobilePhoneNumber;


/**
 * 注册
 */
public class RegisterActivity extends BaseActivity {

    @Bind(R.id.country_text_view) TextView mCountryTextView;
    @Bind(R.id.region_code_text) TextView mRegionCodeTextView;
    @Bind(R.id.selected_country_layout) View mSelectedCountryLayout;
    @Bind(R.id.mobile_phone_edit) EditText mobilePhoneEdit;
    @Bind(R.id.auth_code_et) EditText authCodeEt;
    @Bind(R.id.send_message_text) TextView sendMessageText;
    @Bind(R.id.new_password_edit) EditText newPasswordEdit;
    @Bind(R.id.invitation_code_edit) EditText invitationCodeEdit;
    @Bind(R.id.register_protocol_view) TextView registerProtocolView;
    @Bind(R.id.apply_button) Button applyButton;

    private int mRegionCode = 86; // 默认中国地址
    private RegisterViewModel mViewModel;
    private GT3GeetestUtilsBind mGt3GeetestUtils;

    public static void launch(View view) {
        Activity activity = (Activity) view.getContext();
        ActivityCompat.startActivityForResult(
                activity,
                new Intent(activity, RegisterActivity.class),
                C.REQ_MOBILE_CODE,
                ActivityOptionsCompat.makeSceneTransitionAnimation(activity, view,
                        activity.getString(R.string.transition_name_mobile_number)).toBundle()
        );
    }

    @Override
    protected int getLayoutID() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        return R.layout.activity_register;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_register);

        mViewModel = ViewModelProviders.of(this).get(RegisterViewModel.class);

        // 初始化极验
        initGeetestConfigure();

        // 选择地区
        mSelectedCountryLayout.setOnClickListener(v ->
                SelectedListActivity.launch(this, C.VALUE_REGION_TYPE));

        // 发送短信验证码
        sendMessageText.setOnClickListener(v -> sendMessageCode());

        // 注册
        applyButton.setOnClickListener(v -> registerAccount());

        // 免责
        registerProtocolView.setOnClickListener(v -> WebViewActivity.freeStatement(this));

        // 发送短信结果
        initSendMesCallResult();
    }

    private void initSendMesCallResult() {
        mViewModel.getSendMsmCall().observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, R.string.sending_verification_code);
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
            }
        });
    }

    private void initGeetestConfigure() {
        mGt3GeetestUtils = new GT3GeetestUtilsBind(this);
        mGt3GeetestUtils.setDebug(BuildConfig.DEBUG);
        mGt3GeetestUtils.setTimeout(15000);
        mGt3GeetestUtils.setWebviewTimeout(10000);
    }

    private void sendMessageCode() {
        String phone = mobilePhoneEdit.getText().toString();
        if (verifyMobilePhoneNumber(phone)) {
            mGt3GeetestUtils.showLoadingDialog(this, null);
            mGt3GeetestUtils.setDialogTouch(false);
            mViewModel.startVerification(phone, mRegionCode).observe(this, resource -> {
                if (resource.state == Resource.Status.SUCCESS) {
                    mGt3GeetestUtils.gtSetApi1Json(resource.source);
                    continueVerify();
                } else {
                    Androids.makeText(resource.message);
                }
            });
        }
    }

    private void continueVerify() {
        String captchaURL = BuildConfig.BASE_URL + "user/api1";
        String validateURL = BuildConfig.BASE_URL + "user/api2";
        mGt3GeetestUtils.getGeetest(this, captchaURL, validateURL, null, new GT3GeetestBindListener() {

            @Override
            public boolean gt3SetIsCustom() {
                return true;
            }

            @Override
            public void gt3GetDialogResult(boolean status, String result) {
                if (status) {
                    try {
                        JSONObject json = new JSONObject(result);
                        String challenge = json.getString("geetest_challenge");
                        String validate = json.getString("geetest_validate");
                        String code = json.getString("geetest_seccode");
                        mViewModel.submitVerificationResult(challenge, validate, code)
                                .observe(RegisterActivity.this, resource -> {
                                    if (resource.state == Resource.Status.SUCCESS) {
                                        mGt3GeetestUtils.gt3TestFinish();
                                        mGt3GeetestUtils.setGtCallBack(() -> mViewModel.sendMessage());
                                    } else {
                                        mGt3GeetestUtils.gt3TestClose();
                                    }
                                });
                    } catch (Exception e) {
                        Androids.makeText(e.getMessage());
                    }
                } else {
                    mGt3GeetestUtils.gt3TestClose();
                }
            }
        });
    }

    private void registerAccount() {
        String phone = mobilePhoneEdit.getText().toString();
        String password = newPasswordEdit.getText().toString();
        String invitationCode = invitationCodeEdit.getText().toString();
        String code = authCodeEt.getText().toString();
        mViewModel.register(phone, password, mRegionCode, invitationCode, code).observe(
                this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(this, R.string.registering);
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);

                        if (resource.state == Resource.Status.SUCCESS) {
                            setResult(RESULT_OK, new Intent().putExtra(C.EXTRA_MOBILE, phone));
                            ActivityCompat.finishAfterTransition(this);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == C.REQ_REGION_COIN_TYPE) {
                CountryCodeList.DataBean.ListBean bean = (CountryCodeList.DataBean.ListBean)
                        data.getSerializableExtra(C.EXTRA_REGION);
                mCountryTextView.setText(bean.getZh());
                mRegionCode = bean.getCode();
                mRegionCodeTextView.setText("+" + mRegionCode);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mGt3GeetestUtils.cancelUtils();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mGt3GeetestUtils.changeDialogLayout();
    }
}
